import os
import asyncio
import aiohttp
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
from typing import List, Optional
import json
import zipfile
from datetime import datetime

app = FastAPI(title="小诺机器人图片下载器", version="1.0.0")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class SearchRequest(BaseModel):
    keyword: str = "小诺机器人"
    limit: int = 20
    resolution: Optional[str] = None
    style: Optional[str] = None
    format: Optional[str] = None

class DownloadRequest(BaseModel):
    urls: List[str]
    filename: Optional[str] = None

# 模拟图片数据（实际项目中可替换为真实API）
MOCK_IMAGES = [
    {
        "id": 1,
        "url": "https://via.placeholder.com/400x300/4CAF50/ffffff?text=小诺机器人1",
        "title": "小诺机器人 卡通版",
        "resolution": "400x300",
        "format": "jpg",
        "size": "45KB"
    },
    {
        "id": 2,
        "url": "https://via.placeholder.com/600x400/2196F3/ffffff?text=小诺机器人2",
        "title": "小诺机器人 科技风",
        "resolution": "600x400",
        "format": "jpg",
        "size": "78KB"
    },
    {
        "id": 3,
        "url": "https://via.placeholder.com/800x600/FF9800/ffffff?text=小诺机器人3",
        "title": "小诺机器人 高清版",
        "resolution": "800x600",
        "format": "png",
        "size": "156KB"
    },
    {
        "id": 4,
        "url": "https://via.placeholder.com/500x500/9C27B0/ffffff?text=小诺机器人4",
        "title": "小诺机器人 方形图",
        "resolution": "500x500",
        "format": "jpg",
        "size": "62KB"
    },
    {
        "id": 5,
        "url": "https://via.placeholder.com/1024x768/F44336/ffffff?text=小诺机器人5",
        "title": "小诺机器人 壁纸级",
        "resolution": "1024x768",
        "format": "jpg",
        "size": "234KB"
    }
]

@app.get("/")
async def root():
    return {"message": "小诺机器人图片下载器 API 运行中"}

@app.post("/api/search")
async def search_images(request: SearchRequest):
    """搜索图片"""
    # 实际项目中这里应该调用真实的图片API
    # 这里使用模拟数据
    filtered_images = MOCK_IMAGES
    
    if request.resolution:
        filtered_images = [img for img in filtered_images if request.resolution in img["resolution"]]
    
    if request.format:
        filtered_images = [img for img in filtered_images if img["format"] == request.format]
    
    return {
        "success": True,
        "data": filtered_images[:request.limit],
        "total": len(filtered_images)
    }

@app.post("/api/download")
async def download_images(request: DownloadRequest):
    """下载图片并创建ZIP包"""
    try:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        zip_filename = f"小诺机器人图片_{timestamp}.zip"
        zip_path = os.path.join("downloads", zip_filename)
        
        os.makedirs("downloads", exist_ok=True)
        
        async with aiohttp.ClientSession() as session:
            with zipfile.ZipFile(zip_path, 'w') as zip_file:
                for idx, url in enumerate(request.urls):
                    try:
                        async with session.get(url) as response:
                            if response.status == 200:
                                image_data = await response.read()
                                image_filename = f"image_{idx+1}.jpg"
                                zip_file.writestr(image_filename, image_data)
                    except Exception as e:
                        print(f"下载图片失败: {url}, 错误: {e}")
        
        return {
            "success": True,
            "filename": zip_filename,
            "download_url": f"/api/download/{zip_filename}"
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/download/{filename}")
async def get_download_file(filename: str):
    """获取下载文件"""
    file_path = os.path.join("downloads", filename)
    if os.path.exists(file_path):
        return FileResponse(
            file_path,
            media_type='application/zip',
            filename=filename
        )
    else:
        raise HTTPException(status_code=404, detail="文件不存在")

@app.get("/api/downloads")
async def list_downloads():
    """列出已下载的文件"""
    downloads_dir = "downloads"
    if not os.path.exists(downloads_dir):
        return {"success": True, "files": []}
    
    files = []
    for filename in os.listdir(downloads_dir):
        if filename.endswith('.zip'):
            file_path = os.path.join(downloads_dir, filename)
            files.append({
                "filename": filename,
                "size": os.path.getsize(file_path),
                "created": datetime.fromtimestamp(os.path.getctime(file_path)).isoformat()
            })
    
    return {"success": True, "files": sorted(files, key=lambda x: x["created"], reverse=True)}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
